<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-Type: text/html;charset=utf-8");

/**
 * Class Content
 */
class Content extends MY_Controller {
    
    public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form', 'url'));
    }

    public function file()
    {
        $this->load->view('content/upload_form', array('error' => ' ' ));
    }
	  public function file()
    {
        $this->load->view('content/test');
    }
	
    /**
     * 文件处理
     */
    //请求样例:http://192.168.7.197:8090/?c=content&m=upload&merCode=602260&time=20180309131711&sign=9bcd0897bd3140016e68e9ee9316a4fa
    public function do_upload()
    {
          try{
            $this->load->library('Tool');
            $this->load->helper('func');
            $this->load->library('RedisHandle');
            $this->load->database();
            $params['merCode'] = $_GET['merCode'];
            $params['time'] = $_GET['time'];
            $params['sign'] = $_GET['sign'];
            $params['key'] =$_GET['key'];
            $param['floder']= urldecode($_GET['floder']);
			if($param['floder']==''){
				$param['floder']=$params['merCode'];
			}
            //必填参数校验
            mustParams($params);
            $response = Tool::checkSign($params);//签名验证
            if($response['code'] == 0){        
            //判断是否有分类
            if($param['floder']==''){
                $config['upload_path'] = FCPATH.'uploads/'.$params['merCode'];
            }else{
                if(!file_exists( FCPATH.'uploads/'.$param['floder'])){
                    mkdir(FCPATH.'uploads/'.$param['floder'],0777);
                }
                $config['upload_path'] = FCPATH.'uploads/'.$param['floder'];

            }
             if(!file_exists($config['upload_path']))
            {
                mkdir($config['upload_path'],0777);
            }
            $config['allowed_types'] = self::commonUpload;
            $config['max_size'] = '100000';
            $config['max_width'] = '1024';
            $config['max_height'] = '768';

            $this->load->library('upload', $config);
            //文件类型校验
            $type = explode('|',$config['allowed_types']);
            $str = $_FILES['file']['type'];
            $subType = substr($str,strpos($str,'/')+1);
            if(!in_array($subType,$type)){
                echo json_exit(10005,'文件类型错误');
            }          
            $this->upload->initialize($config);            
            if ($_FILES["file"]["error"] > 0) {
                echo  json_exit(10001,$_FILES["file"]["error"]);
			}else{
                if(file_exists(FCPATH.'uploads/'.$param['floder'].'/'.$_FILES['file']['name'])){
                    echo  json_exit(10002,$_FILES["file"]["name"].'文件已存在');           
                }
                $status = $this->upload->do_pload('file');
                if($status){
                    $fileId = date('YmdHis').mt_rand(1000, 9999);//文件存储id
                    $fileTime=date("Y-m-d H:i:s");//文件存储id
                    $fileMd5 = md5($fileId);
                    $fileName = $_FILES['file']['name'];//文件名
                    $fileSize = $_FILES['file']['size'];
                    
                    if($param['floder']==''){
                         //带参数的请求url
                        $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId;
                    }else{
                         $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId.'&floder='.$param['floder'];
                    }
                        $data = array(
                        'vid' => $fileId,
                        'merCode'=> $params['merCode'],
                        'filename' => $fileName,
                        'time' => $fileTime,
                        'md5' =>$fileMd5,
                        'size'=>$fileSize,
                          );
                    // 生成这样的SQL代码: INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')                  
					$res= $this->db->insert('file_information', $data);               
                    $res = $this->db->affected_rows();
                    if($res){
                        $redis = RedisHandle::getInstance(); //存储$fileId
                        $key = RedisHandle::getKey($fileId);
                        $redis->set($key,$fileName);
						RedisHandle::close();
						$vid = $fileId;
						$muid = 123456;
						$merCode = $params['merCode'];
						$time = date('YmdHis');
						$key = md5($time);
						$data = "merCode=".$merCode."&muid=".$muid."&vid=".$vid."&time=".$time;
						$sign = md5($data);
						echo json_exit(0,'ok',array('vid'=>$fileId,'md5'=>$fileMd5,'url'=>$requestUrl,'testUrl'=>$requestUrl.'&muid='.$muid.'&time='.$time.'&sign='.$sign));
                    }else{
                        echo json_encode(array('code'=>201,'message'=>"存储出错",'info'));
                    }                                   
                }else{
                    echo  json_exit(10001,$_FILES["file"]["error"]);
                }
            }
           }else{
                json_exit(10003,'签名不通过');
           }            
         }catch(Exception $e){
           json_exit(10006, $e->getMessage());         
        }     
    }
	
	/** php 接收流文件 
	* @param String $file 接收后保存的文件名 
	* @return boolean 
	*/
	 public function download(){ 
	 	$this->load->library('Tool');
        $this->load->helper('func');
        $this->load->library('RedisHandle');
        $this->load->database();
        $streamData = file_get_contents('php://input'); 

        $params['merCode'] = $_GET['merCode'];
        $params['time'] = $_GET['time'];
        $params['sign'] = $_GET['sign'];

        $param['floder']= urldecode($_GET['floder']);

            //必填参数校验
        mustParams($params);
        $response = Tool::checkSign($params);//签名验证
        if($response['code'] == 0){
        	//判断是否有分类
            	if($param['floder']==''){
	                if(!file_exists( FCPATH.'uploads/'.$params['merCode'])){
	                    mkdir( FCPATH.'uploads/'.$params['merCode'],0777);	                    
	                }
	                $upload_path = FCPATH.'uploads/'.$params['merCode'];   
	                $floder = $params['merCode'];
           	 	}else{
	                if(!file_exists( FCPATH.'uploads/'.$param['floder'])){
	                    mkdir(FCPATH.'uploads/'.$param['floder'],0777) ;       
	                }
	            	$upload_path = FCPATH.'uploads/'.$param['floder']; 
	            	$floder = $param['floder'];
             	}
             	//var_dump( $params['merCode']);die;
             	//文件处理
            	$streamData = isset($GLOBALS['HTTP_RAW_POST_DATA'])? $GLOBALS['HTTP_RAW_POST_DATA'] : ''; 
            	if(empty($streamData)){ 
			   	 	$streamData = file_get_contents('php://input'); 

			  //  	 	$json=json_decode($input,true); 
					// $base=base64_decode($json['info']); 
			 	 } 
			 	if($streamData!=''){ 
				    $prev_name = date('YmdHis');

					$receiveFile = $upload_path.'/'.$prev_name.'.zip'; 

				    $ret = file_put_contents($receiveFile, $streamData, true);

			  	}else{ 
			   	 	$ret = false; 
			    } 
			    $fileId = date('YmdHis').mt_rand(1000, 9999);//文件存储id
			    $fileTime=date("Y-m-d H:i:s");
                $fileMd5 = md5($fileId);
                $filename =$prev_name.'.zip';

                if($floder==''){
                   $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId; //带参数的请求url
                }else{
                    $requestUrl = self::requestCdn.'&merCode='.$params['merCode'].'&vid='.$fileId.'&floder='.$param['floder'];
                }
                 
                   $data = array(
                        'vid' => $fileId,
                        'merCode'=> $params['merCode'],
                        'filename' => $filename,
                        'time' => $fileTime,
                        'md5' =>$fileMd5,
                        'size'=>$ret,
                        'floder'=> $floder
                          );

                    // 生成这样的SQL代码:
                    //   INSERT INTO mytable (title, name, date) VALUES ('{$title}', '{$name}', '{$date}')
                   $res= $this->db->insert('file_information', $data);
                   $res = $this->db->affected_rows();
                if($res!=''){
                	// $redis = RedisHandle::getInstance(); //存储$fileId
                 //    $key = RedisHandle::getKey($fileId);
                 //    $redis->set($key,$fileId);
                    $vid = $fileId;
                    $muid = 123456;
                    $merCode = $params['merCode'];
                    $time = date('YmdHis');
                    $key = md5($time);
                    $data = "merCode=".$merCode."&muid=".$muid."&vid=".$vid."&time=".$time;
                    $sign = md5($data);
                    RedisHandle::close();
                    echo json_exit(0,'ok',array('vid'=>$fileId,'md5'=>$fileMd5,'url'=>$requestUrl,'testUrl'=>$requestUrl.'&muid='.$muid.'&time='.$time.'&sign='.$sign));

                }else{
                	 echo json_encode(array('code'=>201,'message'=>"存储出错",'info'));
                }		  
        }
	}

}
